<template>
  <div class="custom-input" :class="{'has-border': border}">
    <van-field
      clearable
      v-bind="$attrs"
      v-on="$listeners"
    >
      <van-button slot="button" size="small" type="info" :class="{'disabled': isStart}" v-if="button" @click="$emit('send-sms')" :disalbed="isStart">{{buttonText}}</van-button>
    </van-field>

    <slot></slot>
  </div>
</template>

<script>
  export default {
    name: "custom-input",
    data () {
      return {
        buttonText: '发送验证码',
        isStart: false,
        curCount: this.count
      }
    },
    inheritAttrs: false, // 当前根组件不继承传过来的参数，除了class，直接把传过来的参数传给当前组件的子组件
    props: {
      button: {
        type: Boolean,
        default: false
      },
      count: {
        type: Number,
        default: 60
      },
      sendStatus: {
        type: Boolean,
        default: false
      },
      border: {
        type: Boolean,
        default: true
      }
    },
    watch: {
      sendStatus(val) {
        if (val) this.sendSms();
      }
    },
    mounted() {

    },
    methods: {
      sendSms () {
        this.isStart = true;
        let timeId = setInterval(() => {
          if (this.curCount === 0) {
            this.buttonText = '发送验证码';
            this.curCount = this.count;
            this.isStart = false;
            this.$emit('update:sendStatus', false);
            clearInterval(timeId);
            return;
          }
          this.buttonText = this.curCount;
          this.curCount--;
        }, 1000)
      }
    }
  }
</script>

<style scoped lang="scss">
  .custom-input {
    overflow: hidden;
    &.has-border {
      .van-field {
        border: 1px solid $colorGrey2;
        border-radius: $radius;
      }
    }
  }
</style>
